package com.btkjgc.service.impl;

import com.btkjgc.controller.BaseController;
import com.btkjgc.models.Function;
import com.btkjgc.models.LeftMenu;
import com.btkjgc.models.RoleFunction;
import com.btkjgc.service.intf.LeftBarManager_Intf;
import com.btkjgc.utils.FtlOperationUtil;
import com.btkjgc.utils.HibernateUtil;
import com.btkjgc.utils.LogUtils;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import java.util.*;

/**
 * Created by _ESE on 2015/2/3.
 */
@Component
public class LeftBarManager_Impl implements LeftBarManager_Intf
{

	public BaseController baseController;
	Logger logger = Logger.getLogger(LeftBarManager_Impl.class);

	@SuppressWarnings("unchecked")
	@Override
	public void insertRoleFunction(String roleid, String menuid)
	{
		String hql = "select DISTINCT function from Function function, LeftMenu leftMenu where leftMenu.id="
				+ menuid
				+ " and function.url=leftMenu.url and function.pagelevel=1";
		// select DISTINCT leftMenu from LeftMenu leftMenu, RoleFunction
		// roleFunction, Function function where roleFunction.roleid
		List<Function> function = HibernateUtil.executeQuery(hql, null);
		if (function != null && function.size() == 1)
		{
			RoleFunction roleFunction = new RoleFunction();
			roleFunction.setRoleid(Integer.parseInt(roleid));
			roleFunction.setFunction(function.get(0).getId());
			HibernateUtil.save(roleFunction);
		}
	}

	@Override
	public Map<Integer, Integer> getMenuFunctionMap(
			List<LeftMenu> allLeftMenuList)
	{
		Map<Integer, Integer> menuFunctionMap = new HashMap<Integer, Integer>();
		for (LeftMenu leftMenu : allLeftMenuList)
		{
			if (leftMenu.getUrl() != null && leftMenu.getUrl().length() > 0)
			{
				String hql = "FROM Function WHERE url=?";
				try
				{
					Function function = (Function) HibernateUtil.objectQuery(
							hql, new String[] { leftMenu.getUrl() });
					if (function != null)
						menuFunctionMap.put(leftMenu.getId(), function.getId());
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}
		return menuFunctionMap;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LeftMenu> getRawLeftMenu()
	{
		String hql = "select DISTINCT leftMenu from LeftMenu leftMenu order by leftMenu.index";

		List<LeftMenu> rawLeftMenu = HibernateUtil.executeQuery(hql, null);

		Map<Integer, LeftMenu> indexMenuMap = new HashMap<Integer, LeftMenu>();
		for (LeftMenu menu : rawLeftMenu)
		{
			indexMenuMap.put(menu.getIndex(), menu);
		}

		List<LeftMenu> roots = new ArrayList<LeftMenu>();
		for (LeftMenu menu : rawLeftMenu)
		{
			if (menu.getParentid() == 0)
			{
				roots.add(menu);
			}
			else
			{
				LeftMenu parent = indexMenuMap.get(menu.getParentid());
				if (parent != null)
				{
					parent.getSubmenus().add(menu);
				}
			}
		}

		return roots;
	}

	@Override
	public void updateLeftMenu(String id, String oldUrl, String url, String text)
	{
		if (!FtlOperationUtil.isNull(url) && !url.startsWith("/"))
			url = "/" + url;
		if (!FtlOperationUtil.isNull(oldUrl) && !oldUrl.startsWith("/"))
			oldUrl = "/" + oldUrl;

		String hql = "";
		String param[] = null;
		if (!FtlOperationUtil.isNull(url))
		{
			hql = "update LeftMenu set url=?, text=? where id=?";
			param = new String[] { url, text, id };
		}
		else
		{
			hql = "update LeftMenu set text=? where id=?";
			param = new String[] { text, id };
		}
		HibernateUtil.executeUpdate(hql, param);

		hql = "from LeftMenu where id = ?";
		if (FtlOperationUtil.isNull(oldUrl))
		{ // 原来url为空
			if (!FtlOperationUtil.isNull(url))
			{ // 新的url不为空
				// 添加function、rolefunction
				// function_t中插入一条记录，url = url,pageLevel = 1
				Function function = new Function();
				function.setName("page");
				function.setModule(text);// module暂时设置成和本身一致
				function.setUrl(url);
				function.setCname(text);
				function.setPagelevel(true);

				HibernateUtil.save(function);

				// role_function_t中插入一条新的记录，role_id = min_role_id，function_id =
				// hql取
				hql = "select max(id) from Function";
				int functionId = HibernateUtil.executeCountQuery(hql, null);

				RoleFunction roleFunction = new RoleFunction();
				roleFunction.setRoleid(5);// 暂时都是等级5
				roleFunction.setFunction(functionId);
				HibernateUtil.save(roleFunction);
			}
		}
		else
		{// 原来url不为空
			if (FtlOperationUtil.isNull(url))
			{ // 新的url为空
				// 删除function、rolefunction
				hql = "from Function where url=? and pageLevel=1";
				Function function = (Function) HibernateUtil.objectQuery(hql,
						new String[] { url });
				int functionid = function.getId();

				hql = "delete from Function where id=?";
				HibernateUtil.executeUpdate(hql,
						new String[] { functionid + "" });
				hql = "delete from RoleFunction where function=?";
				HibernateUtil.executeUpdate(hql,
						new String[] { functionid + "" });
			}
			else
			{
				// update function,rolefunction
				hql = "update Function set url=?, cname=? where url=? and pageLevel=1";
				HibernateUtil.executeUpdate(hql, new String[] { url, text,
						oldUrl });
			}
		}
	}

	@Override
	public void deleteById(String id)
	{
		String hql = "from LeftMenu where id=?";
		LeftMenu leftMenu = (LeftMenu) HibernateUtil.objectQuery(hql,
				new String[] { id });

		if (!FtlOperationUtil.isNull(leftMenu.getUrl()))
		{// url非空，需要到function和role_function中删除对应项
			hql = "from Function where url=? and pageLevel=1";
			Function function = (Function) HibernateUtil.objectQuery(hql,
					new String[] { leftMenu.getUrl() });
			if (function != null)
			{
				Integer functionid = function.getId();
				hql = "delete from RoleFunction where function=?";
				HibernateUtil.executeUpdate(hql,
						new String[] { functionid.toString() });

				hql = "delete from Function where url=? and pageLevel=1";
				HibernateUtil.executeUpdate(hql,
						new String[] { function.getUrl() });
			}
		}

		hql = "delete from LeftMenu where id=?";
		HibernateUtil.executeUpdate(hql, new String[] { id });
	}

	@Override
	public void updateLeftMenu(HttpServletRequest request, Integer id,
			Integer index, Integer parent_index, Integer level)
	{
		String hql = "update LeftMenu set index=?, parentid=?, level=? where id=?";
		String param[] = { index.toString(), parent_index.toString(),
				level.toString(), id.toString() };
		HibernateUtil.executeUpdate(hql, param);
		// logger.info("id: "+id+" ,index: "+index+" ,parent_index: "+parent_index+" ,level: "+level);
	}

	@Override
	public void insertLeftMenu(HttpServletRequest request, int parent_index,
			String text, String url, int level, String icon, String module,
			int min_role_id)
	{
		String hql = "select max(id) from LeftMenu";
		int id = HibernateUtil.executeCountQuery(hql, null) + 1;
		// left_menu_t中插入一条新的记录，parent_id = parent_index
		LeftMenu leftMenu = new LeftMenu();
		leftMenu.setId(id);
		leftMenu.setIndex(id);
		leftMenu.setParentid(parent_index);
		leftMenu.setText(text);
		if (url != null && url.trim().length() > 0)
		{
			if (url.startsWith("/"))
				leftMenu.setUrl(url.trim());
			else
				leftMenu.setUrl("/" + url.trim());
		}
		leftMenu.setLevel(level);
		leftMenu.setIcon(icon);
		leftMenu.setNeedend(false);

		HibernateUtil.save(leftMenu);

		if (url != null && !url.isEmpty())
		{
			// function_t中插入一条记录，url = url,pageLevel = 1
			Function function = new Function();
			function.setName("page");
			if (level == 1)
				module = text;
			function.setModule(module);
			if (!url.startsWith("/"))
				url = "/" + url;
			function.setUrl(url);
			function.setCname(text);
			function.setPagelevel(true);

			HibernateUtil.save(function);

			// role_function_t中插入一条新的记录，role_id = min_role_id，function_id = hql取
			hql = "select max(id) from Function";
			int functionId = HibernateUtil.executeCountQuery(hql, null);

			RoleFunction roleFunction = new RoleFunction();
			roleFunction.setRoleid(min_role_id);
			roleFunction.setFunction(functionId);
			HibernateUtil.save(roleFunction);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<LeftMenu> getLeftMenuByRoleId(int roleId)
	{
		String hql0 = "select DISTINCT leftMenu from LeftMenu leftMenu, RoleFunction roleFunction, Function function where roleFunction.roleid="
				+ roleId
				+ " and roleFunction.function=function.id and function.url=leftMenu.url order by leftMenu.id";
		/**
		 * 首先把所有rolefunction权限可以查看的menu添加到rawLeftMenu中，有重复
		 * */
		List<LeftMenu> rawLeftMenu = HibernateUtil.executeQuery(hql0, null);

		hql0 = "from LeftMenu";
		List<LeftMenu> allLeftMenu = HibernateUtil.executeQuery(hql0, null);
		Map<Integer, LeftMenu> index_menu_map = new HashMap<>();
		for (LeftMenu menu : allLeftMenu)
		{
			index_menu_map.put(menu.getIndex(), menu);
		}

		if (rawLeftMenu != null)
		{
			// 需要查两遍父节点
			List<LeftMenu> secondLeftMenu = new ArrayList<>();
			for (LeftMenu lm : rawLeftMenu)
			{
				if (lm.getParentid() != 0)
				{
					LeftMenu temp = index_menu_map.get(lm.getParentid());
					if (temp != null)
					{
						secondLeftMenu.add(temp);
						// rawLeftMenu.add(temp);
					}
				}
			}
			rawLeftMenu.addAll(secondLeftMenu);

			for (LeftMenu lm : secondLeftMenu)
			{
				if (lm.getParentid() != 0)
				{
					LeftMenu temp = index_menu_map.get(lm.getParentid());
					if (temp != null)
					{
						rawLeftMenu.add(temp);
					}
				}
			}
		}

		List<LeftMenu> newMenu = new ArrayList<>();// 去重之后的left_menu
		List<LeftMenu> roots = new ArrayList<LeftMenu>();

		/**
		 * rawLeftMenu去重，包含到menus中
		 * */
		HashMap<Integer, LeftMenu> menus = new HashMap<Integer, LeftMenu>();
		for (LeftMenu menu : rawLeftMenu)
		{
			if (!menus.containsKey(menu.getIndex()))
			{
				menus.put(menu.getIndex(), menu);
				newMenu.add(menu);
			}
		}
		rawLeftMenu = newMenu;
		// LeftMenu设置一级菜单和子菜单？？
		for (LeftMenu menu : rawLeftMenu)
		{
			if (menu.getParentid() == 0)
			{
				roots.add(menu);
			}
			else
			{
				LeftMenu parent = menus.get(menu.getParentid());
				if (parent != null)
				{
					parent.getSubmenus().add(menu);
				}
			}
		}

		List<LeftMenu> menulist = new ArrayList<LeftMenu>();

		ComparatorMenu comparator = new ComparatorMenu();
		Collections.sort(roots, comparator);

		for (LeftMenu l1 : roots)
		{

			if (l1.valid())
			{
				LogUtils.dump("1", l1);
				menulist.add(l1);
				Collections.sort(l1.getSubmenus(), comparator);// 对子菜单进行排序
				if (l1.getSubmenus().size() > 0)// 有子菜单
				{
					l1.getSubmenus().get(l1.getSubmenus().size() - 1)
							.setNeedend(true);// 二级菜单结尾
				}

				for (LeftMenu l2 : l1.getSubmenus())
				{
					if (l2.valid())
					{
						LogUtils.dump("2", l2);

						Collections.sort(l2.getSubmenus(), comparator);
						if (l2.getSubmenus().size() > 0)
						{
							l2.getSubmenus().get(l2.getSubmenus().size() - 1)
									.setNeedend(true);// 三级菜单结尾
						}
						for (LeftMenu l3 : l2.getSubmenus())
						{
							if (l3.valid())
							{
								LogUtils.dump("3", l3);

							}
						}
					}
				}
			}
		}
		return menulist;
	}

	@SuppressWarnings("rawtypes")
	public class ComparatorMenu implements Comparator
	{

		public int compare(Object arg0, Object arg1)
		{
			LeftMenu leftMenu0 = (LeftMenu) arg0;
			LeftMenu leftMenu1 = (LeftMenu) arg1;

			return leftMenu0.getIndex().compareTo(leftMenu1.getIndex());
		}
	}

	/**
	 * 根据 request.getRequestURI() 加载哪种侧边栏
	 */
	@Override
	public ModelAndView addLeftBar(HttpServletRequest request, ModelAndView mv)
	{
		if (baseController == null)
		{
			baseController = new BaseController();
		}
		if (true)
		{// isNeedLeftBar(request)
			baseController.LeftBar(mv, request);
		}
		// if (isNeedMainLeftBar(request)) {
		// baseController.MainLeftBar(mv, request);
		// }

		return mv;
	}

	/**
	 * 根据 request.getRequestURI() 判断是否需要加载 LeftBar
	 */
	@Override
	public boolean isNeedLeftBar(HttpServletRequest request)
	{
		String hql = "select count(*) from LeftMenu where url=?";
		String param[] = { String.valueOf(request.getRequestURI()) };

		return HibernateUtil.executeCountQuery(hql, param) > 0 ? true : false;
	}

	/**
	 * 根据 request.getRequestURI() 判断是否需要加载 LeftBar
	 */
	@Override
	public boolean isNeedMainLeftBar(HttpServletRequest request)
	{
		String hql = "select count(*) from MainLeftMenu where url=?";
		String param[] = { String.valueOf(request.getRequestURI()) };

		return HibernateUtil.executeCountQuery(hql, param) > 0 ? true : false;
	}

}
